import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElSpace,
  ElLink,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { handleTrim } from '~/utils/util'

import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { accomplishEnum, periodEnum } from '~/store/oam/tour/typings'
import type { ValuesType } from './typings'

import ProSaasTable from '~/components/ProSaasTable'
import TourTaskInfo from './info'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'

export default defineComponent(function plan() {
  const route = useRoute()
  const activeIdRef = ref<string>()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ValuesType>({})
  const tourState = useVuexGetters('tour', ['accomplishOpt', 'designateOpt', 'periodOpt'])
  const userState = useVuexGetters('user', ['permission'])
  const store = useStore()
  const columns: TableColumnProps<ValuesType>[] = [
    {
      label: '巡视分组名称',
      prop: 'groupName',
      showOverflowTooltip: true,
      minWidth: 200
    },
    {
      label: '责任人',
      prop: 'leadUserName',
      minWidth: 120
    },
    {
      label: '巡视类型',
      prop: 'type',
      showOverflowTooltip: true,
      minWidth: 200
    },
    {
      label: '区域数量',
      prop: 'assetCounts',
      minWidth: 140,
      align: 'center'
    },
    {
      label: '任务开始时间',
      prop: 'beginTime',
      minWidth: 220
    },
    {
      label: '任务结束时间',
      prop: 'endTime',
      minWidth: 220
    },
    {
      label: '完成情况',
      prop: 'completeStatus',
      minWidth: 160,
      render: (_, value) => {
        return <>{completeStatus(value)}</>
      }
    },
    {
      label: '总巡视次数',
      prop: 'patrolCounts',
      minWidth: 160,
      align: 'center'
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 240,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('produce_patrol_task_view') && (
            <ElLink type="primary" onClick={() => infoOpen(row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 详情
            </ElLink>
          )}
          {userState.permission.value.has('produce_patrol_task_remove') && (
            <ElLink type="primary" onClick={() => remove(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(async () => {
    store.dispatch('tour/GetDictionaryAccomplish', 'patrol_task_status')
    store.dispatch('tour/GetDictionaryPeriod', 'patrol_task_cycle')

    const { code, data } = await store.dispatch('tour/GetConfigList')
    if (code === 200) {
      if (data.length > 0) {
        formValues.configId = data[0].id
        proSaasTableRef.value!?.toSearch()
      }
    }

    const res = await store.dispatch('user/GetCurrentTenant')
    if (res.code === 200) {
      window.localStorage.setItem('userinfo', JSON.stringify(res.data))
    }

    if (route.query.id) infoOpen({ id: route.query.id as string })
  })

  const completeStatus = (value: any) => {
    switch (value) {
      case 0:
        return '未开始'
        break
      case 1:
        return '进行中'
        break
      case 2:
        return '已完成'
        break
      case 3:
        return '超时'
        break
    }
  }
  //  详情
  const infoOpen = (row?: ValuesType) => {
    // router.push({ path: '/oam/tour/task/info', query: { id: row?.id } })
    activeIdRef.value = row?.id
  }
  //  删除
  const remove = (row: ValuesType) => {
    ElMessageBox.confirm('确定将选择数据删除?', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('tour/GetPatrolTaskRemoveList', row.id).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.toSearch()
            ElMessage({ type: 'success', message: '操作成功' })
          }
        })
      })
      .catch(() => {})
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  return () => {
    if (activeIdRef.value) {
      return <TourTaskInfo id={activeIdRef.value} goBack={() => infoOpen(undefined)} />
    }

    return (
      <ElCard shadow="never" class="covered-with-content">
        <ProSaasTable<ValuesType>
          ref={proSaasTableRef}
          columns={columns}
          searchParams={{
            groupName:
              formValues.groupName === ''
                ? undefined
                : formValues.groupName && handleTrim(formValues.groupName)
          }}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="tour/GetPatrolTaskList"
          searchformResponsiveCol={[
            <ElFormItem key="completeStatus" prop="completeStatus" label="">
              <ElSelect
                v-model={formValues.completeStatus}
                clearable
                onChange={clearSearchTable}
                placeholder="完成情况"
              >
                {tourState.accomplishOpt?.value?.map((item: accomplishEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="cycle" prop="cycle" label="">
              <ElSelect
                v-model={formValues.cycle}
                clearable
                onChange={clearSearchTable}
                placeholder="查看周期"
              >
                {tourState.periodOpt?.value?.map((item: periodEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="groupName" prop="groupName" label="">
              <ElInput
                v-model={formValues.groupName}
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
                placeholder="巡视名称"
              />
            </ElFormItem>
          ]}
        ></ProSaasTable>
      </ElCard>
    )
  }
})
